import React, { useState, useEffect, useCallback } from "react";
import { Search } from 'react-vant';
import { Cross, ClockO,ArrowLeft } from '@react-vant/icons';
import './search.css';
import axios from "axios";
import { useNavigate, Link } from "react-router-dom";

// 样式常量
const STYLES = {
  searchButton: {
    background: '#007bff',
    color: '#fff',
    border: 'none',
    padding: '6px 12px',
    borderRadius: '4px',
    cursor: 'pointer',
  },
  deleteButton: {
    background: 'none',
    border: 'none',
    cursor: 'pointer',
    color: '#ff4d4f',
  },
  historyItem: {
    padding: '8px 0',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  clearAll: {
    cursor: 'pointer',
  },
};

// 定义美妆数据接口
interface BeautyItem {
  name: string;
  content?: string;
  apply: string;
  imgs: string;
}

const Index: React.FC = () => {
  const [value, setValue] = useState<string>("");
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [showAll, setShowAll] = useState<boolean>(false);
  const [beautyList, setBeautyList] = useState<BeautyItem[]>([]);
  const [filteredBeautyList, setFilteredBeautyList] = useState<BeautyItem[]>([]);
  const navigate = useNavigate();

  // 初始化：加载本地存储的搜索历史
  useEffect(() => {
    try {
      const storedHistory = localStorage.getItem("searchHistory");
      if (storedHistory) {
        setSearchHistory(JSON.parse(storedHistory));
      }
    } catch (error) {
      console.error("Failed to load search history:", error);
    }
  }, []);

  // 获取后端beauty数据
  const getBeautyData = async () => {
    try {
      const res = await axios.post<{ list: BeautyItem[] }>("http://localhost:3000/auth/list");
      setBeautyList(res.data.list);
      setFilteredBeautyList(res.data.list); // 初始时显示所有美妆数据
    } catch (error) {
      console.error("Failed to fetch beauty data:", error);
    }
  };

  useEffect(() => {
    getBeautyData();
  }, []);

  // 实时过滤美妆列表
  useEffect(() => {
    if (value.trim() === "") {
      setFilteredBeautyList(beautyList); // 输入为空时显示所有美妆数据
    } else {
      const filtered = beautyList.filter((item) =>
        item.name.toLowerCase().includes(value.toLowerCase())
      );
      setFilteredBeautyList(filtered);
    }
  }, [value, beautyList]);

  // 处理搜索提交
  const handleSearch = useCallback(
    (searchValue: string) => {
      if (searchValue.trim() === "") return;

      const updatedHistory = [
        searchValue,
        ...searchHistory.filter((item) => item !== searchValue),
      ].slice(0, 10);

      setSearchHistory(updatedHistory);
      localStorage.setItem("searchHistory", JSON.stringify(updatedHistory));
      setValue("");
      navigate(`/result?query=${encodeURIComponent(searchValue)}`);
    },
    [searchHistory, navigate]
  );

  // 处理输入框变化
  const onChange = useCallback((val: string) => {
    setValue(val);
  }, []);

  // 清除所有搜索历史
  const clearHistory = useCallback(() => {
    setSearchHistory([]);
    localStorage.removeItem("searchHistory");
    setShowAll(false);
  }, []);

  // 删除单条搜索记录
  const deleteHistoryItem = useCallback(
    (index: number) => {
      const updatedHistory = searchHistory.filter((_, i) => i !== index);
      setSearchHistory(updatedHistory);
      localStorage.setItem("searchHistory", JSON.stringify(updatedHistory));
    },
    [searchHistory]
  );

  // 切换显示全部/折叠
  const toggleShowAll = useCallback(() => {
    setShowAll((prev) => !prev);
  }, []);
  
  // 确定显示的搜索记录
  const displayedHistory = showAll ? searchHistory : searchHistory.slice(0, 3);
  const handleBack = () => {
    window.history.go(-1);
  };
  return (
    <div className="box">
      {/* 搜索输入框 */}
      <div className="top" style={{display:"flex"}}>
      <ArrowLeft
          
          onClick={handleBack}
          style={{ marginRight: '12px', fontSize: '24px', cursor: 'pointer', color: '#333',marginTop:"15px" }}
        />
        <Search
          value={value}
          onChange={onChange}
          clearable
          placeholder="搜索或提问"
          action={
            <button
              onClick={() => handleSearch(value)}
              style={STYLES.searchButton}
              className="search-button"
            >
              搜索
            </button>
          }
        />
      </div>

      {/* 动态显示搜索结果或初始数据 */}
      {value.trim() === "" ? (
        <>
          <div className="center">
            <div className="center-top">
              <h3>最近搜索</h3>
              <p
                onClick={clearHistory}
                style={STYLES.clearAll}
                className="clear-all"
              >
                移除所有
              </p>
            </div>
            <div className="search-history">
              {searchHistory.length > 0 ? (
                <ul className="history-list">
                  {displayedHistory.map((item, index) => (
                    <li
                      key={index}
                      style={STYLES.historyItem}
                      className="history-item"
                    >
                      <span>
                        <ClockO /> {item}
                      </span>
                      <button
                        onClick={() => deleteHistoryItem(index)}
                        style={STYLES.deleteButton}
                        className="delete-button"
                      >
                        <Cross />
                      </button>
                    </li>
                  ))}
                  {searchHistory.length > 3 && (
                    <p
                      onClick={toggleShowAll}
                      style={STYLES.clearAll}
                      className="toggle-history"
                    >
                      {showAll
                        ? `折叠历史记录(${searchHistory.length})`
                        : `查看所有搜索历史(${searchHistory.length})`}
                    </p>
                  )}
                </ul>
              ) : (
                <p>暂无搜索记录</p>
              )}
            </div>
          </div>
          <div className="bottom">
            <div className="bottom-top">
              <h2>热门评论</h2>
              <p>查看全部</p>
            </div>
            <div className="bottom-center">
              {filteredBeautyList.length > 0 ? (
                <ul className="beauty-list beauty-list-horizontal">
                  {filteredBeautyList.map((item, index) => (
                    <li key={index} className="beauty-item beauty-item-card">
                      <Link
                        to={`/detail?name=${encodeURIComponent(item.name)}&content=${encodeURIComponent(item.content || "")}&apply=${encodeURIComponent(item.apply)}&imgs=${encodeURIComponent(item.imgs)}`}
                        style={{ display: "block", textDecoration: "none", color: "inherit" }}
                      >
                        <img
                          src={item.imgs}
                          alt={item.name}
                          className="beauty-item-image"
                        />
                        <div className="beauty-item-info">
                          <span className="beauty-item-name">{item.name}</span>
                          <span className="beauty-item-price">{item.apply}</span>
                        </div>
                      </Link>
                    </li>
                  ))}
                </ul>
              ) : (
                <p>暂无美妆数据</p>
              )}
            </div>
          </div>
        </>
      ) : (
        filteredBeautyList.length > 0 ? (
          <div className="bottom">
            <ul className="beauty-list">
              {filteredBeautyList.map((item, index) => (
                <li key={index} className="beauty-item">
                  <Link
                    to={`/detail?name=${encodeURIComponent(item.name)}&content=${encodeURIComponent(item.content || "")}&apply=${encodeURIComponent(item.apply)}&imgs=${encodeURIComponent(item.imgs)}`}
                    style={{ display: "block", textDecoration: "none", color: "inherit" }}
                    className="beauty-item-name"
                  >
                    {item.name}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        ) : (
          <div className="bottom">
            <p>无匹配结果</p>
          </div>
        )
      )}
    </div>
  );
};

export default Index;